#!/bin/bash

  star=★
 round=⊙
 colon=：

   all=綜合運勢
  love=愛情運勢
  work=工作狀況
 money=理財投資
health=健康指數
  talk=商談指數
 color=幸運顏色
number=幸運數字
zodiac=速配星座

zodiac_array=(\
Aries Taurus Gemini Cancer Leo Virgo Libra Scorpio Sagittarius Capricorn Aquarius Pisces
)

zodiac_array2=(\
aries taurus gemini cancer leo virgo libra scorpio sagittarius capricorn aquarius pisces
muyang jinniu shuangzi juxie shizi chunv tiancheng tianxie sheshou mojie shuiping shuangyu
)

zodiac_full_array=(\
"牡羊座 Aries (03/21 - 04/19)" \
"金牛座 Taurus (04/20 - 05/20)" \
"雙子座 Gemini (05/21 - 06/21)" \
"巨蟹座 Cancer (06/22 - 07/22)" \
"獅子座 Leo (07/23 - 08/22)" \
"處女座 Virgo (08/23 - 09/22)" \
"天秤座 Libra (09/23 - 10/23)" \
"天蠍座 Scorpio (10/24 - 11/22)" \
"射手座 Sagittarius (11/23 - 12/21)" \
"魔羯座 Capricorn (12/22 - 01/19)" \
"水瓶座 Aquarius (01/20 - 02/18)" \
"雙魚座 Pisces (02/19 - 03/20)" \
)

g_date=
g_zodiac=
g_tempfile=

# param: title
# return: stars
function get_star() {
    local count=`grep $1 $g_tempfile | awk -F star.gif '{print NF-1}'`
    echo $count
}

# param: title
# return: formatted content
function get_star_formatted() {
    local c_star=`get_star $1`
    echo -n $round$1$colon
    if [ $c_star -eq 5 ]; then
        echo -en "\033[1;31m"
    fi
    for (( i=1; i<=$c_star; i++ )); do
        echo -n $star
    done
    if [ $c_star -eq 5 ]; then
        echo -en "\033[m"
    fi
}

# param: title
# return: content
function get_content() {
    local line=`grep $1 $g_tempfile`
    local content=`echo $line | sed 's/<p>/ /; s/<\/p>/ /' | awk '{print $3}'`
    echo $content
}

# param: title
# return: formatted content
function get_content_formatted() {
    local c_content=`get_content $1`
    echo -n $round$1$colon$c_content
}

# return major contents
function get_major_contents() {
    local first=`sed -n "/lotconts/{n; s/<.*>//g; p}" $g_tempfile`
    local second=`sed -n "/lotconts/{n; n; s/<.*>//g; p}" $g_tempfile`
    echo "　　$first\n　　$second\n"
}

# param: date (yyymmdd|-n|0|+n|invalid)
# return: yyymmdd or "-1"
function parse_date() {
    if [ "$1" = "0" ]; then
        echo `date +"%Y%m%d"`
    elif [[ $1 =~ ^[+!-][0-9]+$ ]]; then
        echo `date +"%Y%m%d" -d "$1 day"`
    elif [[ $1 =~ ^[0-9]{8}$ ]]; then
        if date -d "$1" &> /dev/null; then
            echo "$1"
        fi
    else
        echo "-1"
    fi
}

# param: zodiac string
# return: zodiac index or -1
function parse_zodiac() {
    local arrlen=${#zodiac_array2[*]}
    local zodiac=`echo $1 | tr [A-Z] [a-z]`
    for (( i=0; i< arrlen; i++ )); do
        if [ $zodiac = ${zodiac_array2[$i]} ]; then
            break
        fi
    done
    if [ $i -eq $arrlen ]; then
        echo -1
    else
        (( i = $i % ($arrlen/2) ))
        echo $i
    fi
}

function usage() {
    echo "Usage: ./astrology.sh [-d yyyymmdd|0|+n|-n] [-z aquarius|shuiping]"
}

function interactive() {
    # get date
    while true; do
        echo -n "Please enter date (yyyymmdd/0/+n/-n): "
        read
        g_date=`parse_date $REPLY`
        if [ $g_date != "-1" ]; then
            break
        fi
    done
    # get zodiac
    PS3="Please enter zodiac: "
    COLUMNS=20  # force one option per line
    select opt in ${zodiac_array[*]}; do
        case $opt in
        "Aries")
            g_zodiac=0
            break
        ;;
        "Taurus")
            g_zodiac=1
            break
        ;;
        "Taurus")
            g_zodiac=2
            break
        ;;
        "Cancer")
            g_zodiac=3
            break
        ;;
        "Leo")
            g_zodiac=4
            break
        ;;
        "Virgo")
            g_zodiac=5
            break
        ;;
        "Libra")
            g_zodiac=6
            break
        ;;
        "Scorpio")
            g_zodiac=7
            break
        ;;
        "Sagittarius")
            g_zodiac=8
            break
        ;;
        "Capricorn")
            g_zodiac=9
            break
        ;;
        "Aquarius")
            g_zodiac=10
            break
        ;;
        "Pisces")
            g_zodiac=11
            break
        ;;
        esac
    done
    COLUMNS=  # restore
}

function report() {
    # http://mindcity.sina.com.tw/MC_data/west/MC-12horos/day/20110101/aquarius.shtml
    local url=`printf "http://mindcity.sina.com.tw/MC_data/west/MC-12horos/day/%s/%s.shtml" $g_date ${zodiac_array2[$g_zodiac]}`
    echo "Please wait..."
    # --max-redirect=0 to only try once for easier processing.
    wget $url -q --max-redirect=0 -O ${zodiac_array2[$g_zodiac]}.shtml
    local ret=$?
    if [ $ret -ne 0 ]; then
        if [ $ret -eq 4 ]; then
            echo "There seems to be a network error... :(" >&2
        elif [ $ret -eq 8 ]; then
            echo "The content you are trying to get is not ready yet :)" >&2
        fi
        exit 1
    fi
    g_tempfile=${zodiac_array2[$g_zodiac]}.shtml

    echo
    echo `date -d "$g_date" +"%Y-%m-%d "` ${zodiac_full_array[$g_zodiac]}
    echo
    echo ${zodiac_full_array[$g_zodiac]}
    echo
    echo `get_star_formatted $all`
    echo `get_star_formatted $love`
    echo `get_star_formatted $work`
    echo `get_star_formatted $money`
    echo `get_content_formatted $health`
    echo `get_content_formatted $talk`
    echo `get_content_formatted $color`
    echo `get_content_formatted $number`
    echo `get_content_formatted $zodiac`
    echo
    echo -e `get_major_contents`
    echo
    
    rm $g_tempfile
}

function parse_options() {
    if [ $# -eq 0 ]; then
        interactive
    else
        while getopts :d:z: opt; do
            case "$opt" in
            d)
                g_date=`parse_date $OPTARG`
                ;;
            z)
                g_zodiac=`parse_zodiac $OPTARG`
                ;;
            esac
        done
        if [ -z $g_date ] || [ $g_date = "-1" ] \
            || [ -z $g_zodiac ] || [ $g_zodiac -eq -1 ]; then
            usage
            exit 1
        fi
    fi
    # process
    report
}

echo "astrology.sh  v0.2        (C)2011 gonwan"
parse_options $*

